import axios from "axios";
import { getToken } from "@/utils/token";
import { Message, MessageBox } from "element-ui";
import store from "@/store";

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 10000,
});
// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      config.headers["Authorization"] = token;
    }
    return config;
  },
  (err) => Promise.reject(new Error(err))
);

// 响应拦截器
request.interceptors.response.use(
  (res) => {
    if (res.data.code < 50000) {
      return res.data.data;
    }
    console.log("xxxx", res.data);
    Message.error(res.data.msg);
    return Promise.reject(new Error(res.data.msg));
  },
  (error) => {
    let { message, response } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (response.status === 403) {
      MessageBox.confirm("登录信息已经过期，是否重新登录", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        store.dispatch("user/logout");
      });
      return Promise.reject(new Error(message));
    } else if (message.includes("Request failed with status code")) {
      message = `系统接口${message.substr(message.length - 3)}异常`;
    }
    Message.error(message);
    return Promise.reject(new Error(message));
  }
);
export default request;
